<template>
  <div
    class="detailPage mg-10 pd-20"
    v-loading="showloading"
    element-loading-text="加载中,请稍后..."
  >
    <div class="backBtn">
      <Back width="18px" hight="18px" />
      <ElButton class="btn" @click="handleBack()">返回</ElButton>
    </div>
    <ElTabs v-model="activeName" class="detail-form">
      <ElTabPane :label="route.query.id ? '编辑计划' : '新增计划'" name="first">
        <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rules">
          <ElRow style="width: 50%">
            <ElCol :span="24">
              <ElFormItem label="所属组织" prop="organizationId">
                <ElTreeSelect
                  v-model="ruleForm.organizationId"
                  :data="treeData"
                  :props="{
                    children: 'children',
                    label: 'organizationName',
                    disabled: (data) =>
                      data.status === false || data.disabled == 1,
                  }"
                  node-key="id"
                  :render-after-expand="false"
                  check-strictly
                  placeholder="请选择所属组织"
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="24">
              <ElFormItem label="计划名称" prop="planName">
                <ElInput
                  v-model="ruleForm.planName"
                  placeholder="请输入计划名称"
                  @input="(value) => spaceInput('planName', value)"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="24">
              <ElFormItem label="执行航线" prop="airLineId">
                <div v-if="ruleForm.airLineId" class="grey-text">
                  <span>{{ airLineName }}</span>
                  <ElButton link type="primary" @click="airlineClick"
                    >更改航线</ElButton
                  >
                </div>
                <ElButton
                  class="bluebg-btn"
                  style="width: 100%"
                  v-else
                  @click="airlineClick"
                  ><Plus class="size-5" />选择航线</ElButton
                >
              </ElFormItem></ElCol
            >
            <ElCol :span="24" v-if="ruleForm.airLineId">
              <ElFormItem label="无人机型号" prop="modelName">
                <ElInput
                  v-model="ruleForm.modelName"
                  placeholder="请重新选择航线"
                  disabled
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="24">
              <ElFormItem label="任务下发" prop="issued">
                <div style="width: 100%">
                  <ElButton
                    :class="ruleForm.issuedBtn == '1' ? 'blue-btn' : ''"
                    @click="issuedClick('1')"
                    >机场</ElButton
                  >
                  <!-- <ElButton
                    :class="ruleForm.issuedBtn == '2' ? 'blue-btn' : ''"
                    @click="issuedClick('2')"
                    >飞手</ElButton
                  > -->
                  <div
                    v-if="ruleForm.issued"
                    class="grey-text"
                    style="margin-top: 10px"
                  >
                    <span>{{ ruleForm.issued }}</span>
                    <ElButton
                      link
                      type="primary"
                      @click="airportClick(ruleForm.issuedBtn)"
                      >{{
                        ruleForm.issuedBtn == "1" ? "更改机场" : "更改飞手"
                      }}</ElButton
                    >
                  </div>
                  <div v-else>
                    <ElButton
                      style="width: 100%; margin-top: 10px"
                      class="bluebg-btn"
                      @click="airportClick('1')"
                      v-if="ruleForm.issuedBtn == '1'"
                      ><Plus class="size-5" />选择机场</ElButton
                    >
                    <ElButton
                      v-if="ruleForm.issuedBtn == '2'"
                      style="width: 100%; margin-top: 10px"
                      class="bluebg-btn"
                      @click="airportClick('2')"
                      ><Plus class="size-5" />选择飞手</ElButton
                    >
                  </div>
                </div>
              </ElFormItem>
            </ElCol>
            <ElCol :span="24">
              <!-- :prop="ruleForm.executeType == '0' ? 'mode' : 'time'" -->
              <ElFormItem label="执行模式" prop="executeType">
                <div style="width: 100%">
                  <ElButton
                    :class="executeTypeButton == '0' ? 'blue-btn' : ''"
                    @click="modeClick('0')"
                    :disabled="route.query.id ? true : false"
                    >立即执行</ElButton
                  >
                  <ElButton
                    :class="executeTypeButton == '1' ? 'blue-btn' : ''"
                    @click="modeClick('1')"
                    :disabled="route.query.id ? true : false"
                    >单次定时</ElButton
                  >
                  <ElButton
                    :class="executeTypeButton == '2' ? 'blue-btn' : ''"
                    @click="modeClick('2')"
                    :disabled="route.query.id ? true : false"
                    >重复定时</ElButton
                  >
                  <div
                    v-if="ruleForm.executeType == '1'"
                    style="padding: 5px; margin-top: 10px"
                    class="displayflex"
                  >
                    <ElFormItem
                      prop="time1"
                      style="width: calc(50% - 5px); margin-bottom: 0"
                    >
                      <ElDatePicker
                        style="width: 100%"
                        v-model="ruleForm.time1"
                        type="date"
                        :disabled-date="disabledDate"
                        placeholder="请选择年月日"
                        :default-value="new Date()"
                        @change="handleDateChange"
                      ></ElDatePicker>
                    </ElFormItem>
                    <ElFormItem
                      prop="time2"
                      style="
                        width: calc(50% - 5px);
                        margin-bottom: 0;
                        margin-left: 10px;
                      "
                    >
                      <el-time-picker
                        style="width: 100%"
                        v-model="ruleForm.time2"
                        format="HH:mm"
                        value-format="HH:mm:ss"
                        :default-value="getDefaultTimeValue()"
                        :disabled-hours="getDisabledHours"
                        :disabled-minutes="getDisabledMinutes"
                        placeholder="请选择时分"
                        :disabled-seconds="disabledSeconds"
                      ></el-time-picker>
                    </ElFormItem>
                  </div>
                  <div
                    v-if="executeTypeButton == '2'"
                    style="
                      padding: 10px;
                      margin-top: 10px;
                      background: #f0f2f5;
                      border-radius: 4px;
                    "
                  >
                    <ElFormItem label="重复频率" prop="days">
                      <div style="display: flex; width: 100%">
                        <span style="width: 6%"> 每 </span>
                        <ElInputNumber
                          style="width: 46%"
                          :controls="false"
                          :min="1"
                          :max="365"
                          v-model="ruleForm.days"
                          placeholder="请输入"
                          :value-on-clear="null"
                        ></ElInputNumber>
                        <ElSelect
                          style="width: 46%; margin-left: 2%"
                          v-model="ruleForm.frequencyNum"
                          placeholder="请选择"
                        >
                          <ElOption
                            v-for="item in frequencyData"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </ElSelect>
                      </div>
                      <div class="weekStyle" v-if="ruleForm.frequencyNum == 0">
                        <p
                          v-for="(item, index) in weekList"
                          :key="index"
                          :class="weekactive == item.value ? 'active' : ''"
                          @click="weekactive = item.value"
                        >
                          {{ item.label }}
                        </p>
                      </div>
                      <div class="weekStyle" v-if="ruleForm.frequencyNum == 1">
                        <p
                          v-for="(item, index) in 31"
                          :key="index"
                          :class="dateactive == item ? 'active' : ''"
                          @click="dateactive = item"
                        >
                          {{ item }}
                        </p>
                      </div>
                    </ElFormItem>
                    <ElFormItem
                      label="执行日期"
                      prop="frequencyDate"
                      style="margin-top: 15px"
                    >
                      <ElDatePicker
                        v-model="ruleForm.frequencyDate"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :disabled-date="disabledDateRange"
                        @calendar-change="handleDateChange"
                      />
                    </ElFormItem>
                    <ElFormItem
                      label="执行时间"
                      prop="time"
                      style="margin-top: 15px"
                    >
                      <ElTimePicker
                        style="width: 100%"
                        v-model="ruleForm.time"
                        :default-value="new Date()"
                        format="HH:mm"
                        value-format="HH:mm:ss"
                        placeholder="请选择时间"
                        type="time"
                        :disabled-seconds="disabledSeconds"
                      />
                    </ElFormItem>
                  </div>
                </div>
              </ElFormItem>
            </ElCol>
            <ElCol :span="24">
              <ElFormItem label="自动断点续飞" prop="status">
                <ElSwitch v-model="ruleForm.status" />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
        <div class="footer">
          <ElButton @click="resetForm(ruleFormRef)">清空</ElButton>
          <ElButton
            v-if="router.currentRoute.value.query.id"
            type="primary"
            @click="editForm"
          >
            确定
          </ElButton>
          <ElButton v-else type="primary" @click="addForm"> 确定 </ElButton>
        </div>
      </ElTabPane>
    </ElTabs>
    <airline ref="airlineDialog" @airlineRow="getAirline"></airline>
    <airport ref="airportDialog" @airportRow="getAirport"></airport>
    <flyhand ref="flyhandDialog" @flyhandRow="getflyhand"></flyhand>
    <!-- <atregulartime ref="timeDialog" @timeRow="gettime"></atregulartime> -->
  </div>
</template>
<script lang="ts" setup>
import {
  ElButton,
  ElTabs,
  ElTabPane,
  ElRow,
  ElCol,
  ElMessageBox,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElRadioGroup,
  ElRadio,
  ElMessage,
  ElSelect,
  ElOption,
  ElTreeSelect,
  ElSwitch,
  ElDatePicker,
  ElTimePicker,
} from "element-plus";
// import { Back } from '@vben/icons';
import { reactive, ref, onMounted, computed } from "vue";
import { router } from "#/router";
import { useRoute } from "vue-router";
import airline from "./airline.vue";
import airport from "./airport.vue";
import flyhand from "./flyhand.vue";
// import atregulartime from './atregulartime.vue';
import {
  addOnSiteInspection,
  editOnsiteInspection,
  getOnSiteInspectionDetail,
} from "#/api/task/patrolScheme";
import { getOrganizationsByUserId } from "#/api/sys/organization";
import { getAirportList } from "#/api/sys/equipment";
import dayjs from "dayjs";

// 限制日期选择范围为今天之后的30天内（不能选择过去的时间）
const disabledDate = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置为今天的开始时间

  const thirtyDaysLater = new Date();
  thirtyDaysLater.setDate(today.getDate() + 30);
  thirtyDaysLater.setHours(0, 0, 0, 0); // 设置为30天后的开始时间

  const selectedDate = new Date(date);
  selectedDate.setHours(0, 0, 0, 0); // 设置为选择日期的开始时间

  // 禁用今天之前的日期和30天之后的日期
  return (
    selectedDate.getTime() < today.getTime() ||
    selectedDate.getTime() > thirtyDaysLater.getTime()
  );
};

// 禁用秒选择，只允许选择00秒
const disabledSeconds = () => {
  // 返回1-59的数组，这样就只能选择00秒
  return Array.from({ length: 59 }, (_, i) => i + 1);
};

// 限制日期范围选择（今天至未来180天）
const disabledDateRange = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置为今天的开始时间

  const hundredEightyDaysLater = new Date();
  hundredEightyDaysLater.setDate(today.getDate() + 180);
  hundredEightyDaysLater.setHours(0, 0, 0, 0); // 设置为180天后的开始时间

  const selectedDate = new Date(date);
  selectedDate.setHours(0, 0, 0, 0); // 设置为选择日期的开始时间

  // 禁用今天之前的日期和180天之后的日期
  return (
    selectedDate.getTime() < today.getTime() ||
    selectedDate.getTime() > hundredEightyDaysLater.getTime()
  );
};

// 处理日期范围变化，确保最小间隔为2天
const handleDateChange = (val) => {
  if (val && val.length === 2) {
    const [startDate, endDate] = val;
    if (startDate && endDate) {
      const timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
      const diffDays = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

      // 如果选择的日期间隔小于2天，自动调整结束日期
      if (diffDays < 2) {
        const adjustedEndDate = new Date(startDate);
        adjustedEndDate.setDate(startDate.getDate() + 2);

        // 检查调整后的日期是否超出180天范围
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const hundredEightyDaysLater = new Date();
        hundredEightyDaysLater.setDate(today.getDate() + 180);
        hundredEightyDaysLater.setHours(0, 0, 0, 0);

        if (adjustedEndDate.getTime() <= hundredEightyDaysLater.getTime()) {
          ruleForm.frequencyDate = [startDate, adjustedEndDate];
          ElMessage.warning("日期跨度不能少于2天");
        } else {
          // 如果调整后的日期超出范围，则提示用户重新选择
          ruleForm.frequencyDate = [];
          ElMessage.error("日期跨度不能少于2天且不能超出180天范围，请重新选择");
        }
      }
    }
  }
};

// 获取默认时间值
const getDefaultTimeValue = () => {
  const selectedDate = ruleForm.time1 ? new Date(ruleForm.time1) : new Date();
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  selectedDate.setHours(0, 0, 0, 0);

  // 如果选择的是今天，设置为当前时间多加两分钟
  if (selectedDate.getTime() === today.getTime()) {
    const now = new Date();
    // 设置为当前时间多加两分钟
    now.setMinutes(now.getMinutes() + 2);
    return now;
  } else {
    // 如果不是今天，设置为00:00:00
    return new Date(
      selectedDate.getFullYear(),
      selectedDate.getMonth(),
      selectedDate.getDate(),
      0,
      0,
      0
    );
  }
};

// 获取禁用的小时
const getDisabledHours = () => {
  const selectedDate = ruleForm.time1 ? new Date(ruleForm.time1) : new Date();
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  selectedDate.setHours(0, 0, 0, 0);

  // 只有当选择的是今天时才限制小时
  if (selectedDate.getTime() === today.getTime()) {
    const now = new Date();
    const currentHour = now.getHours();
    // 返回今天之前的所有小时数组
    return Array.from({ length: currentHour }, (_, i) => i);
  }
  // 非今天不限制
  return [];
};

// 获取禁用的分钟
const getDisabledMinutes = (hour) => {
  const selectedDate = ruleForm.time1 ? new Date(ruleForm.time1) : new Date();
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  selectedDate.setHours(0, 0, 0, 0);

  // 只有当选择的是今天且选择的小时是当前小时时才限制分钟
  if (selectedDate.getTime() === today.getTime()) {
    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();

    // 如果选择的是当前小时，则禁用当前分钟之前的所有分钟（包括当前分钟）
    if (hour === currentHour) {
      return Array.from({ length: currentMinute + 1 }, (_, i) => i);
    }
    // 如果选择的是今天但小时早于当前小时，则禁用所有分钟
    else if (hour < currentHour) {
      // 返回0-59的所有分钟
      return Array.from({ length: 60 }, (_, i) => i);
    }
  }
  // 其他情况不限制分钟
  return [];
};

const spaceInput = (field: string, value: string) => {
  // 过滤空格
  ruleForm[field] = value.replace(/\s+/g, "");
};
const loading = ref(false);
const showloading = ref(false);
const activeName = ref("first");
const route = useRoute();
const weekactive = ref(null);
const dateactive = ref("");
const ruleFormRef = ref();
const ruleForm = reactive<RuleForm>({
  id: router.currentRoute.value.query.id || "",
  organizationId: "",
  planName: "",
  airlineCode: null,
  // 新增品牌系列型号字段
  modelName: "", //无人机型号
  brandId: "",
  seriesId: "",
  modelId: "",
  // end
  status: false,
  issuedBtn: "1",
  issued: "",
  executeType: "0",
  time: "", //
  frequencyDate: [],
  frequencyNum: "2",
  airportId: "",
  days: null,
  flyhandId: "",
  airLineId: "",
  // 单次定时
  time1: "",
  time2: "",
  singleDate: "",
});
const frequencyData = [
  {
    value: "2",
    label: "天",
  },
  {
    value: "0",
    label: "周",
  },
  {
    value: "1",
    label: "月",
  },
];
const weekList = [
  {
    value: "1",
    label: "周一",
  },
  {
    value: "2",
    label: "周二",
  },
  {
    value: "3",
    label: "周三",
  },
  {
    value: "4",
    label: "周四",
  },
  {
    value: "5",
    label: "周五",
  },
  {
    value: "6",
    label: "周六",
  },
  {
    value: "0",
    label: "周日",
  },
];

// 自定义校验日期范围
const validateDateRange = (rule, value, callback) => {
  // 添加类型检查和安全处理
  if (!value || !Array.isArray(value) || value.length !== 2) {
    callback(new Error("请选择开始日期和结束日期"));
    return;
  }

  // 安全地获取开始和结束日期
  let startDate, endDate;

  try {
    // 确保 startDate 是有效的 Date 对象
    if (value[0] instanceof Date) {
      startDate = value[0];
    } else if (typeof value[0] === "string") {
      startDate = new Date(value[0]);
    } else {
      callback(new Error("开始日期格式不正确"));
      return;
    }

    // 确保 endDate 是有效的 Date 对象
    if (value[1] instanceof Date) {
      endDate = value[1];
    } else if (typeof value[1] === "string") {
      endDate = new Date(value[1]);
    } else {
      callback(new Error("结束日期格式不正确"));
      return;
    }

    // 检查日期对象是否有效
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      callback(new Error("日期格式不正确"));
      return;
    }
  } catch (error) {
    callback(new Error("日期格式不正确"));
    return;
  }

  // 检查日期间隔是否至少2天
  const timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
  const diffDays = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

  if (diffDays < 2) {
    callback(new Error("日期跨度必须大于2天"));
    return;
  }

  // 检查日期是否在有效范围内
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const hundredEightyDaysLater = new Date();
  hundredEightyDaysLater.setDate(today.getDate() + 180);
  hundredEightyDaysLater.setHours(0, 0, 0, 0);

  // 检查开始日期
  const startCheck = new Date(startDate);
  startCheck.setHours(0, 0, 0, 0);
  if (
    startCheck.getTime() < today.getTime() ||
    startCheck.getTime() > hundredEightyDaysLater.getTime()
  ) {
    callback(new Error("开始日期必须在今天至未来180天内"));
    return;
  }

  // 检查结束日期
  const endCheck = new Date(endDate);
  endCheck.setHours(0, 0, 0, 0);
  if (
    endCheck.getTime() < today.getTime() ||
    endCheck.getTime() > hundredEightyDaysLater.getTime()
  ) {
    callback(new Error("结束日期必须在今天至未来180天内"));
    return;
  }

  callback();
};

// 自定义校验执行时间
const validateTime = (rule, value, callback) => {
  if (ruleForm.executeType === "2" && (!value || value === "")) {
    callback(new Error("请选择执行时间"));
  } else {
    callback();
  }
};

// 自定义校验重复频率
const validateDays = (rule, value, callback) => {
  if (ruleForm.executeType === "2" && (!value || value === null)) {
    callback(new Error("请填写重复频率"));
  } else {
    callback();
  }
};

// 自定义校验频率类型
const validateFrequencyNum = (rule, value, callback) => {
  if (ruleForm.executeType === "2" && (!value || value === "")) {
    callback(new Error("请选择频率类型"));
  } else {
    callback();
  }
};

const rules = reactive({
  planName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
  ],
  organizationId: [
    { required: true, message: "请选择所属组织", trigger: "change" },
  ],
  airLineId: [{ required: true, message: "请选择航线", trigger: "change" }],
  status: [
    { required: true, message: "请选择自动断点续飞状态", trigger: "change" },
  ],
  issued: [{ required: true, message: "请选择任务下发", trigger: "change" }],
  executeType: [
    { required: true, message: "请选择执行模式", trigger: "change" },
  ],
  days: [
    { required: true, message: "请填写频率", trigger: "blur" },
    { validator: validateDays, trigger: "blur" },
  ],
  frequencyDate: [
    { required: true, message: "请选择日期", trigger: "change" },
    { validator: validateDateRange, trigger: "change" },
  ],
  time: [
    { required: true, message: "请选择时间", trigger: "change" },
    { validator: validateTime, trigger: "change" },
  ],
  time1: [{ required: true, message: "请选择年月日", trigger: "change" }],
  time2: [{ required: true, message: "请选择时分", trigger: "change" }],
});
const airlineModelName = ref(null); // 来自航线
const taskTargetModelName = ref(null); // 来自机场

const treeData = ref([]);
const defaultProps = {
  children: "children",
  label: "organizationName",
};
const airlineDialog = ref();
const airportDialog = ref();
const flyhandDialog = ref();
const timeDialog = ref();
const handleBack = () => {
  router.go(-1);
};
const airlineClick = () => {
  airlineDialog.value.addDialog();
};
const airportClick = (item) => {
  if (item == "1") {
    airportDialog.value.addDialog();
  } else {
    flyhandDialog.value.addDialog();
  }
};
const airLineName = ref("");
const airportName = ref("");
const flyhandName = ref("");
const issuedClick = (item) => {
  ruleForm.issued = "";
  ruleForm.issuedBtn = item;
  if (ruleForm.issuedBtn == "1") {
    ruleForm.issued = airportName.value;
  } else {
    ruleForm.issued = flyhandName.value;
  }
};
const modeClick = (item) => {
  ruleForm.executeType = item;
  executeTypeButton.value = item;
  // if (item == '2') {
  //   timeDialog.value.addDialog();
  // }
};

const checkModelMismatch = () => {
  // 只有选中机场时才校验无人机型号，选中飞手时不校验
  if (ruleForm.issuedBtn !== "1") {
    return false;
  }

  const airline = airlineModelName.value;
  const target = taskTargetModelName.value;

  // 如果任何一个型号为空，则不进行校验
  if (airline == null || target == null) {
    return false;
  }

  // 只有当两个值都存在，并且不相等时才提示
  if (airline !== target) {
    ElMessage({
      message: `
        <div style="color: rgb(48, 49, 51); font-size: 14px;">
          该航线 [<strong style="color: #d32f2f;">${airline}</strong>] 
          与机场无人机型号 [<strong style="color: #d32f2f;">${target}</strong>] 不符，
          请重新选择<strong style="color: rgb(48, 49, 51);"> 航线/机场 </strong>。
        </div>
      `,
      type: "error",
      duration: 5000,
      showClose: true,
      dangerouslyUseHTMLString: true,
      customClass: "custom-warning-message",
    });

    // 返回 true 表示存在不匹配
    return true;
  }

  // 返回 false 表示没有不匹配
  return false;
};

const getAirline = (item) => {
  airLineName.value = item.airlineName;
  ruleForm.airLineId = item.id;
  ruleForm.airlineCode = item.airlineCode;
  // 无人机型号
  ruleForm.modelName = item.modelName;
  ruleForm.modelId = item.modelId;
  ruleForm.brandId = item.brandId;
  ruleForm.seriesId = item.seriesId;
  airlineModelName.value = item.modelName; // 记录航线的型号
  // 比较两个型号
  checkModelMismatch();
};
const getAirport = (item) => {
  ruleForm.issued = item.airportName;
  ruleForm.airportId = item.id;
  airportName.value = item.airportName;
  taskTargetModelName.value = item.modelName; // 记录机场的型号
  // 比较两个型号
  checkModelMismatch();
};
const getflyhand = (item) => {
  ruleForm.issued = item.name;
  flyhandName.value = item.name;
  ruleForm.flyhandId = item.id;
};
const gettime = (item) => {
  ruleForm.time = item;
};

const executeTypeButton = ref("0");
const clearExecutionFields = () => {
  // 清空重复频率相关字段
  ruleForm.days = null;
  ruleForm.frequencyNum = "2";

  // 清空执行日期 - 使用空数组
  ruleForm.frequencyDate = [];

  // 清空执行时间 - 使用空字符串和null
  ruleForm.time = "";
  ruleForm.time1 = "";
  ruleForm.time2 = "";
  ruleForm.singleDate = "";

  // 清空周/日期选择
  weekactive.value = null;
  dateactive.value = "";

  // 强制触发视图更新（确保 Vue 检测到数据变化）
  ruleFormRef.value?.clearValidate([
    "days",
    "frequencyDate",
    "time",
    "time1",
    "time2",
  ]);
};

const resetForm = (formEl) => {
  if (!formEl) return;

  // 判断是否为编辑状态
  const isEditMode = !!router.currentRoute.value.query.id;
  // 保存编辑状态下的执行模式值
  const originalExecuteType = isEditMode ? ruleForm.executeType : "0";

  // 清除表单验证状态(先执行resetFields)
  if (formEl) {
    formEl.resetFields();
  }

  // 重置所有表单字段
  ruleForm.id = router.currentRoute.value.query.id || "";
  ruleForm.organizationId = "";
  ruleForm.planName = "";
  ruleForm.airlineCode = null;
  ruleForm.modelName = "";
  ruleForm.brandId = "";
  ruleForm.seriesId = "";
  ruleForm.modelId = "";
  ruleForm.status = false;
  ruleForm.issuedBtn = "1";
  ruleForm.issued = "";
  // 保持编辑状态下的执行模式不变
  ruleForm.executeType = originalExecuteType;
  ruleForm.airportId = "";
  ruleForm.flyhandId = "";
  ruleForm.airLineId = "";

  // 更新按钮状态变量
  executeTypeButton.value = originalExecuteType;

  // 重置相关的响应式变量（编辑状态下不重置执行模式相关变量）
  airLineName.value = "";
  airportName.value = "";
  flyhandName.value = "";
  airlineModelName.value = null;
  taskTargetModelName.value = null;

  // 特别清空执行相关字段(在resetFields之后执行,确保清空生效)
  clearExecutionFields();
};

// 验证执行时间是否早于当前时间
const validateExecutionTime = () => {
  const now = new Date();

  // 单次定时验证
  if (ruleForm.executeType === "1") {
    if (ruleForm.time1 && ruleForm.time2) {
      // 正确处理日期和时间的组合
      let executionDate;

      if (ruleForm.time2 instanceof Date) {
        // 如果 time2 是 Date 对象
        const dateTimeString =
          dayjs(ruleForm.time1).format("YYYY-MM-DD") + " " + ruleForm.time2;
        executionDate = new Date(dateTimeString);
      } else if (typeof ruleForm.time2 === "string") {
        // 如果 time2 是时间字符串（如 "14:30:00"）
        const dateTimeString =
          dayjs(ruleForm.time1).format("YYYY-MM-DD") + " " + ruleForm.time2;
        executionDate = new Date(dateTimeString);
      } else {
        // 其他情况，尝试直接构造
        executionDate =
          dayjs(ruleForm.time1).format("YYYY-MM-DD") + " " + ruleForm.time2;
      }

      // console.log('executionDate:', executionDate, 'now:', now, 'isBefore:', executionDate < now);

      // 检查日期是否有效
      if (isNaN(executionDate.getTime())) {
        ElMessage.error("执行时间格式不正确");
        return false;
      }

      if (executionDate < now) {
        ElMessage.error("执行时间不能早于当前时间");
        return false;
      }
    }
  }
  // 重复定时验证
  else if (ruleForm.executeType === "2") {
    // 验证重复日期范围
    if (ruleForm.frequencyDate && ruleForm.frequencyDate.length === 2) {
      const [startDate, endDate] = ruleForm.frequencyDate;
      if (startDate && endDate) {
        // 检查开始日期是否早于今天
        const startDateTime = new Date(startDate);
        startDateTime.setHours(0, 0, 0, 0);
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        if (startDateTime < today) {
          ElMessage.error("执行日期不能早于当前日期");
          return false;
        }

        // 如果开始日期是今天，检查执行时间是否早于当前时间
        // if (startDateTime.getTime() === today.getTime() && ruleForm.time) {
        //   // 构造今天的完整执行时间
        //   const todayWithTime = new Date();
        //   if (typeof ruleForm.time === 'string' && ruleForm.time.includes(':')) {
        //     const [hours, minutes, seconds = '0'] = ruleForm.time.split(":").map(Number);
        //     todayWithTime.setHours(hours, minutes, seconds || 0, 0);

        //     if (todayWithTime < now) {
        //       ElMessage.error("执行时间不能早于当前时间");
        //       return false;
        //     }
        //   }
        // }
      }
    }
  }

  return true;
};

let days = "";
let weeks = "";
let months = "";

const editForm = async () => {
  showloading.value = true;
  if (loading.value) return;

  // 验证执行时间
  if (!validateExecutionTime()) {
    showloading.value = false;
    return;
  }

  // 在保存前检查型号是否匹配
  if (checkModelMismatch()) {
    showloading.value = false;
    return; // 如果存在不匹配，阻止保存操作
  }

  if (ruleForm.frequencyNum == "2") {
    days = ruleForm.days;
  }
  if (ruleForm.frequencyNum == "0") {
    weeks = ruleForm.days;
  }
  if (ruleForm.frequencyNum == "1") {
    months = ruleForm.days;
  }
  try {
    loading.value = true;
    await ruleFormRef.value?.validate();
    const params = {
      id: Number(ruleForm.id),
      organizationId: ruleForm.organizationId,
      planName: ruleForm.planName,
      airportId: ruleForm.airportId,
      airlineId: ruleForm.airLineId,
      airlineCode: ruleForm.airlineCode,
      startTime: dayjs(ruleForm.frequencyDate[0]).format("YYYY-MM-DD HH:mm:ss")
        ? dayjs(ruleForm.frequencyDate[0]).format("YYYY-MM-DD HH:mm:ss")
        : "",
      endTime: dayjs(ruleForm.frequencyDate[1]).format("YYYY-MM-DD HH:mm:ss")
        ? dayjs(ruleForm.frequencyDate[1]).format("YYYY-MM-DD HH:mm:ss")
        : "",
      jobType: ruleForm.frequencyNum,
      executeType: ruleForm.executeType,
      days: days,
      months: months,
      weeks: weeks,
      day: dateactive.value,
      week: weekactive.value,
      singleDate:
        dayjs(ruleForm.time1).format("YYYY-MM-DD") + " " + ruleForm.time2,
      time: ruleForm.time, //执行时间
      brandId: ruleForm.brandId,
      seriesId: ruleForm.seriesId,
      modelId: ruleForm.modelId,
    };
    if (ruleForm.executeType !== "1" && params.singleDate) {
      delete params.singleDate;
    }
    const { code, message = "修改失败" } = await editOnsiteInspection(params);
    if (code !== 200) throw new Error(message);
    ElMessage.success("修改成功");
    showloading.value = false;
    resetForm(); // 重置表单
    handleBack(); // 注释掉返回上一页的调用
  } catch (err) {
    // 更详细地显示验证错误信息
    if (err instanceof Error) {
      ElMessage.error(err.message || "表单验证失败，请检查输入内容");
    } else {
      ElMessage.error("表单验证失败，请检查输入内容");
    }
  } finally {
    loading.value = false;
    showloading.value = false;
  }
};

const addForm = async () => {
  if (loading.value) return;

  // 验证执行时间
  if (!validateExecutionTime()) {
    return;
  }

  // 在保存前检查型号是否匹配
  if (checkModelMismatch()) {
    return; // 如果存在不匹配，阻止保存操作
  }

  if (ruleForm.frequencyNum == "2") {
    days = ruleForm.days;
  }
  if (ruleForm.frequencyNum == "0") {
    weeks = ruleForm.days;
  }
  if (ruleForm.frequencyNum == "1") {
    months = ruleForm.days;
  }
  try {
    loading.value = true;
    await ruleFormRef.value?.validate();
    const params = {
      organizationId: ruleForm.organizationId,
      planName: ruleForm.planName,
      airportId: ruleForm.airportId,
      airlineId: ruleForm.airLineId,
      airlineCode: ruleForm.airlineCode,
      startTime: dayjs(ruleForm.frequencyDate[0]).format("YYYY-MM-DD HH:mm:ss")
        ? dayjs(ruleForm.frequencyDate[0]).format("YYYY-MM-DD HH:mm:ss")
        : "",
      endTime: dayjs(ruleForm.frequencyDate[1]).format("YYYY-MM-DD HH:mm:ss")
        ? dayjs(ruleForm.frequencyDate[1]).format("YYYY-MM-DD HH:mm:ss")
        : "",
      jobType: ruleForm.frequencyNum,
      executeType: ruleForm.executeType,
      days: days,
      months: months,
      weeks: weeks,
      day: dateactive.value,
      week: weekactive.value,
      singleDate:
        dayjs(ruleForm.time1).format("YYYY-MM-DD") + " " + ruleForm.time2,
      time: ruleForm.time, //执行时间
      brandId: ruleForm.brandId,
      seriesId: ruleForm.seriesId,
      modelId: ruleForm.modelId,
    };
    if (ruleForm.executeType !== "1" && params.singleDate) {
      delete params.singleDate;
    }
    const { code, msg } = await addOnSiteInspection(params);
    if (code !== 200) {
      ElMessage.error(msg);
      return;
    } else {
      ElMessage.success("添加成功");
      resetForm(); // 重置表单
      handleBack(); // 注释掉返回上一页的调用
    }
  } catch (err) {
    // 更详细地显示验证错误信息
    if (err instanceof Error) {
      ElMessage.error(err.message || "表单验证失败，请检查输入内容");
    } else {
      ElMessage.error("表单验证失败，请检查输入内容");
    }
  } finally {
    loading.value = false;
  }
};

const getTableData = async () => {
  const { data } = await getOrganizationsByUserId();
  treeData.value = data;
};

const airportList = async () => {
  const params = {
    airportName: airportName.value,
    currentPage: 1,
    pageSize: 10,
  };
  try {
    const { data } = await getAirportList(params);
    if (data.records.length > 0) {
      taskTargetModelName.value = data.records[0].modelName;
      // 在数据加载完成后检查型号是否匹配
      checkModelMismatch();
    } else {
      taskTargetModelName.value = null;
    }
  } catch (err) {
    ElMessage.error("加载数据失败");
  }
};

const getDetail = async () => {
  const params = {
    id: ruleForm.id,
  };
  const { data } = await getOnSiteInspectionDetail(params);

  if (data.jobType == "2") {
    ruleForm.days = data.days ? Number(data.days) : null;
  }
  if (data.jobType == "0") {
    ruleForm.days = data.weeks ? Number(data.weeks) : null;
  }
  if (data.jobType == "1") {
    ruleForm.days = data.months ? Number(data.months) : null;
  }

  ruleForm.frequencyNum = data.jobType + "";
  ruleForm.organizationId = data.organizationId;
  ruleForm.planName = data.planName;
  ruleForm.airlineCode = data.airlineCode;
  ruleForm.airportId = data.airportId;
  ruleForm.executeType = data.executeType + "";
  // 执行模式按钮状态
  executeTypeButton.value = data.executeType + "";
  dateactive.value = data.day;
  weekactive.value = data.week;
  ruleForm.time = data.time;

  // 航线数据
  airLineName.value = data.airlineName;
  ruleForm.airLineId = data.airlineId;
  ruleForm.modelName = data.modelName;
  // 设置航线型号用于校验
  airlineModelName.value = data.modelName;

  airportName.value = data.airportName;
  airportList();
  flyhandName.value = "飞手1";
  ruleForm.issued = airportName.value;
  // 设置机场型号用于校验
  // taskTargetModelName.value = data.airportModelName || null;

  // 安全处理日期范围数据
  try {
    if (data.startTime && data.endTime) {
      const startDate = new Date(data.startTime);
      const endDate = new Date(data.endTime);

      // 确保日期有效
      if (!isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
        ruleForm.frequencyDate = [startDate, endDate];
      } else {
        ruleForm.frequencyDate = [];
      }
    } else {
      ruleForm.frequencyDate = [];
    }
  } catch (error) {
    console.warn("日期解析错误:", error);
    ruleForm.frequencyDate = [];
  }

  // 安全地分割 singleDate，避免空值错误
  if (data.singleDate && typeof data.singleDate === "string") {
    const dateParts = data.singleDate.split(" ");
    if (dateParts.length >= 2) {
      ruleForm.time1 = dateParts[0];
      // 将时间字符串转换为 Date 对象，避免 el-time-picker 渲染错误
      const timeString = dateParts[1];
      if (timeString) {
        const [hours, minutes, seconds] = timeString.split(":").map(Number);
        ruleForm.time2 = new Date(0, 0, 0, hours, minutes, seconds);
      } else {
        ruleForm.time2 = new Date();
      }
    }
  } else {
    ruleForm.time1 = "";
    ruleForm.time2 = new Date();
  }

  showloading.value = false;
};

onMounted(() => {
  getTableData();
  if (ruleForm.id) {
    showloading.value = true;
    getDetail();
  }
});
</script>
<style scoped lang="scss">
p {
  margin: 20px 0;
  font-weight: 900;
}

.labelText {
  color: #ccc;
}

img {
  height: 100px;
  margin-top: 10px;
  margin-right: 20px;
}

.displayflex {
  display: flex;
  width: 100%;
  padding: 0 10px;
  background: #f0f2f5;
  border-radius: 4px;

  span {
    margin-right: 20px;
  }

  .el-button {
    color: #1989fa;
  }
}

.searchCol {
  .btn {
    .blue {
      color: #1989fa;
      border: 1px solid #1989fa;
    }
  }

  .bluebtn {
    color: #1989fa;
    background: #e6f1fc;
    border: 1px solid #a3d0fd;
  }
}

.weekStyle {
  display: flex;
  flex-wrap: wrap;
  width: 100%;

  p {
    width: calc(20% - 10px);
    margin: 10px 5px 0;
    font-weight: normal;
    text-align: center;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }

  .active {
    color: #1989fa;
    border-color: #1989fa;
  }
}

:deep(.el-tree-node.is-disabled .el-tree-node__content) {
  color: #c0c4cc;
  cursor: not-allowed;
}

:deep(.el-tree-node.is-disabled .el-tree-node__content:hover) {
  background-color: transparent;
}
</style>